import datetime
import json


class CheckState():
    _ENDORSE = 'endorse'
    _VERIFY = 'verify'
    _DELETE = 'delete'

def resetEformCheckState(eform):
    """
        Set done, verify, endorse date to none,
        set verifyed_id , endorsedby_id to None
    """
    eform.verifiedby_id = None
    eform.endorsedby_id = None
    eform.doneDate = None
    eform.verifiedDate = None
    eform.endorsedDate = None
    eform.save()


def checkCanEndorse(user):
    """
        return {bool}, permission to perform endrose 
    """
    return user.has_perm('eform.can_endorsed')


def checkCanVerify(user):
    """
        return {bool}, permission to perform verify 
    """
    return user.has_perm('eform.can_verified')

def checkCanDelete(user):
    """
        return {bool}, permission to perform delete
    """
    return user.has_perm('eform.delete_eform')

def getCheckFunction(check_state):
    """
    @params {String} check_state, verify|endrose
    RETURN suitable checkfunction {checkCanEndorse | checkCanVerify}
    """
    if not check_state:
        return False
    
    if check_state == CheckState._VERIFY:
        return checkCanVerify
    
    if check_state == CheckState._ENDORSE:
        return checkCanEndorse

    if check_state == CheckState._DELETE:
        return checkCanDelete
    
    return False


def getClientIP(request):
    """EXTRACT AND RETURN CLIENT IP FROM WEB REQUEST"""
    x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
    if x_forwarded_for:
        try:
            ip = x_forwarded_for.split(',')[0]
            return ip
        except Exception as ex:
            print(ex)
            return False
    else:
        return request.META.get('REMOTE_ADDR',False)


def lockEform(eform):
    '''
        lock eform schema after done is clicked
    '''
    try:
        eform.extFormSchema = eform.eformSchema.formSchema
        eform.extTitle = eform.eformSchema.title
        eform.extFormNo = eform.eformSchema.formNo
        eform.extRef = eform.eformSchema.ref
        eform.extIssue = eform.eformSchema.issue
        eform.schema_lock = True
        eform.schemaRetrieveDate = datetime.datetime.now()
        return True
    except Exception as ex:
        return False


def getEformSchema(eform):
    """
        Take eform, check is the schema is locked,
        Return json dumped correct schema 
    """
    formSchema = None
    if eform.schema_lock:
         formSchema = json.dumps(eform.extFormSchema)
        ## use formSchema instead of extFormSchema
        ## if eform is lock use extFormSchema
    else:
        formSchema =  json.dumps(eform.eformSchema.formSchema)
    return formSchema

    
